import type { ItemType } from '@/stores'
import { useCalendarStore } from '@/stores/modules/calendar'

export default function() {
  const calendarStore = useCalendarStore()

  const deleteCalendar = (itemId: string) => {
    console.log(`deleteCalendar itemId:${itemId}`)
    if (!itemId) return
    // #ifdef APP-PLUS
    let itemCalendars = calendarStore.getItemCalendars(itemId)
    let CalendarContract = getCalendarContract()
    let cr = getContentResolver()
    itemCalendars?.forEach(calendarId => {
      console.log(`calendarId:${calendarId}`)
      if(!calendarId) return
      const ContentUris = plus.android.importClass('android.content.ContentUris')

      // 构建删除URI
      const Events = plus.android.importClass("android.provider.CalendarContract$Events");
      // const ContentUris = plus.android.importClass("android.content.ContentUris");
      // const Uri = plus.android.importClass("android.net.Uri");

      // 创建删除URI
      // const deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID);

      // 执行删除操作
      // @ts-ignore
      let deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, parseInt(calendarId))
      // let rows = plus.android.invoke(cr, 'delete', deleteUri, null, null)
      let rows = cr.delete(deleteUri, null, null)
      console.log(rows)
    })

    calendarStore.clearItemCalendars(itemId)
    // #endif
  }

  const insertCalendar = (item: ItemType) => {
    console.log(`insertCalendar item:${item}`)

    // #ifdef APP-PLUS
    plus.android.requestPermissions(
      ['android.permission.WRITE_CALENDAR', 'android.permission.READ_CALENDAR'],
      function(res) {
        console.log('权限申请结果:', JSON.stringify(res))
      },
      function(err) {
        console.log('权限申请失败:', JSON.stringify(err))
      },
    )

    let CalendarContract = getCalendarContract()
    let resolver = getContentResolver()

    // 计算下次更换日期
    let nextReplacementDate = new Date(item.lastReplacementDate)
    nextReplacementDate.setMonth(nextReplacementDate.getMonth() + item.replacementCycle)
    let startMillis = nextReplacementDate.getTime()
    let endMillis = nextReplacementDate.getTime()
    console.log(`startMillis:${startMillis}  ; endMillis:${endMillis}`)

    // Step 1: 插入事件
    let values = getContentValues()
    values.put('calendar_id', 1) // 默认日历ID，注意部分手机可能不是1
    values.put('title', '更换产品:' + item.name)
    // values.put('eventLocation', '嘉兴')
    values.put('allDay', 1)
    values.put('dtstart', startMillis)
    values.put('dtend', endMillis)
    values.put('eventTimezone', 'Asia/Shanghai')
    values.put('hasAlarm', 1)
    // @ts-ignore
    let eventsUri = CalendarContract.Events.CONTENT_URI
    let newEventUri = resolver.insert(eventsUri, values)
    console.log('插入事件 URI: ' + newEventUri)

    let eventId = plus.android.invoke(newEventUri, 'getLastPathSegment')
    console.log(`eventId:${eventId}`)
    if (!eventId) {
      return
    }
    // 把id放到缓存
    calendarStore.addItemCalendar(item.id, eventId)

    addReminder(eventId)
    // printUrlFiled(CalendarContract.Events.CONTENT_URI)

// #endif
  }
  const addReminder = (eventID: string) => {
    if (!eventID) {
      return
    }
    let resolver = getContentResolver()
    let CalendarContract = getCalendarContract()

    try {
      const values = getContentValues()
      values.put('event_id', eventID)
      // 提前15分钟有提醒
      values.put('minutes', 10)
      // @ts-ignore
      values.put('method', CalendarContract.Reminders.METHOD_ALERT)
      // @ts-ignore
      const uri = resolver.insert(CalendarContract.Reminders.CONTENT_URI, values)
      // const uri = plus.android.invoke(resolver, 'insert', CalendarContract.Reminders.CONTENT_URI, values)
      console.log(`addReminder uri:${uri}`)
    } catch (error) {
      console.warn(`提醒方法  失败:`, error)
    }

  }

  // CalendarContract.Reminders.CONTENT_URI
  const printUrlFiled = (uri: any) => {
    console.log(`printUrlFiled`)
    let resolver = getContentResolver()
    // @ts-ignore
    var cursor = plus.android.invoke(resolver, 'query', uri, null, null, null, null)

    console.log(`cursor:${cursor}`)
    let moveToFirst = plus.android.invoke(cursor, 'moveToFirst')
    if (!moveToFirst) {
      console.log(`moveToFirst:${moveToFirst}`)
      return
    }
    do {
      let columnCount = plus.android.invoke(cursor, 'getColumnCount')
      console.log(`columnCount : ${columnCount}`)

      for (let i = 0; i < columnCount; i++) {
        let columnName = plus.android.invoke(cursor, 'getColumnName', i)
        let columnIndex = plus.android.invoke(cursor, 'columnName', columnName)

        // 根据列类型获取值
        let value = ''
        let type = plus.android.invoke(cursor, 'getType', columnIndex)

        switch (type) {
          case 1: // INTEGER
            value = plus.android.invoke(cursor, 'getLong', columnIndex)
            break
          case 2: // FLOAT
            value = plus.android.invoke(cursor, 'getFloat', columnIndex)
            break
          case 3: // STRING
            value = plus.android.invoke(cursor, 'getString', columnIndex)
            break
          case 4: // BLOB
            value = plus.android.invoke(cursor, 'getBlob', columnIndex)
            break
          default:
            value = plus.android.invoke(cursor, 'getString', columnIndex)
            break
        }

        console.log(`${columnName} : ${value}`)
      }
    } while (plus.android.invoke(cursor, 'moveToNext'))
  }

  const getAvailableCalendarId = () => {
    try {
      let resolver = getContentResolver()

      let CalendarContract = plus.android.importClass('android.provider.CalendarContract')
      // @ts-ignore
      let cursor = plus.android.invoke(resolver, 'query', CalendarContract.Reminders.CONTENT_URI, null, null, null, null)

      if (cursor && plus.android.invoke(cursor, 'moveToFirst')) {
        do {
          var id = plus.android.invoke(cursor, 'getInt', 0)
          var displayName = plus.android.invoke(cursor, 'getString', 1)
          var accountName = plus.android.invoke(cursor, 'getString', 2)
          console.log('日历: ID=' + id + ', 名称=' + displayName + ', 账户=' + accountName)

          // 返回第一个找到的日历ID
          plus.android.invoke(cursor, 'close')
          return id
        } while (plus.android.invoke(cursor, 'moveToNext'))
      }

      if (cursor) {
        plus.android.invoke(cursor, 'close')
      }
    } catch (e) {
      console.error('查询日历ID失败: ' + e)
    }
    return null
  }
  const getContentValues = () => {
    let ContentValues = plus.android.importClass('android.content.ContentValues')
    // @ts-ignore
    return new ContentValues()
  }
  const getContentResolver = () => {
    let main = plus.android.runtimeMainActivity()
    // @ts-ignore
    let contentResolver = main.getContentResolver()
    plus.android.importClass(contentResolver)
    return contentResolver
  }

  const getCalendarContract = () => {
    let CalendarContract = plus.android.importClass('android.provider.CalendarContract')
    return CalendarContract
  }

  return { insertCalendar, deleteCalendar }
}